<template src="./data.html">
</template>
<script setup>
import data from '../data.js'
import { getFooterTop, getHeaderBottom } from '../element'
import {
  onMounted, onUnmounted,
  ref, defineProps,
} from 'vue'

const props = defineProps(['count'])
const INCREMENT = props.count
let start = ref(0)
let end = ref(INCREMENT * 2)
const itemRefs = ref([])

function scroll () {
  const firstItem = itemRefs.value[start.value]
  const lastItem = itemRefs.value[end.value - 1]

  if (lastItem.getBoundingClientRect().bottom < getFooterTop()) {
    end.value += INCREMENT
    end.value = Math.min(data.length, end.value)
    start.value = end.value - INCREMENT * 2
    start.value = Math.max(0, start.value)
    end.value = start.value + INCREMENT * 2
  }
  if (firstItem.getBoundingClientRect().top > getHeaderBottom()) {
    start.value -= INCREMENT
    start.value = Math.max(0, start.value)
    end.value = start.value + INCREMENT * 2
  }
}

onMounted(() => document.addEventListener('scroll', scroll))
onUnmounted(() => document.removeEventListener('scroll', scroll))

function setItemRef (el, item) {
  itemRefs.value[data.indexOf(item)] = el
}
</script>
